package com.chinackts.common.exception.handler;

import com.chinackts.common.exception.ApplicationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Primary;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.*;


/**
 * Created by Lianhong_ on 2018/05/21 13:21
 */
@RestControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class GlobalControllerExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalControllerExceptionHandler.class);

    // 通用异常的处理，返回500
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)  // 500
    @ExceptionHandler({Exception.class, RuntimeException.class})
    public RestServiceError handleException(Exception ex) {
        logger.error("系统异常。", ex);
        return RestServiceError.build("9999", ex.getMessage());
    }

    // validator 异常的处理，返回500
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)  // 500
    @ExceptionHandler({BindException.class})
    public RestServiceError handleException(BindException ex) {
        logger.error("validator异常: {}", ex.getFieldError().toString());
        return RestServiceError.build("9998", ex.getFieldError().getDefaultMessage());
    }

    // 业务异常的处理，返回200
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)  // 200
    @ExceptionHandler(ApplicationException.class)
    public RestServiceError handleApplicationException(ApplicationException ex) {
        logger.error("业务异常。", ex);
        return RestServiceError.build(ex.getCode(), ex.getMessage());
    }
}
